package cn.echo.sharding.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 按历史备份拆表
 * @author lonyee
 *
 */
public class HistoryRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        Set<String> collect = new HashSet<>();
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        Date startTime = valueRange.lowerEndpoint();
        Date endTime = valueRange.upperEndpoint();
        
        Calendar calendar = Calendar.getInstance();
        LocalDateTime currDate = LocalDateTime.now();

        while (startTime.getTime()<=endTime.getTime()){
            LocalDateTime shardingDate = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
            long interval = ChronoUnit.MONTHS.between(currDate, shardingDate);
            for (String each : collection) {
            	//2个月前查记录表，2个月内查原表
    			if (interval>=2L) {
    	            if (each.endsWith("history")) {
                        collect.add(each);
    	            }
    			} else {
    				if (!each.endsWith("history")) {
                        collect.add(each);
    				}
                }
            	//当前表和历史表都加入了就没必须循环了
                if (collect.size()>=2) {
                    return collect;
                }
            }
            calendar.setTime(startTime);
            calendar.add(Calendar.DATE, 1);
            startTime = calendar.getTime();
        }
        return collect;
    }
    
}
